var path=require('path');
var fs=require('fs');
var Config=require('./Config');
var fileUtil = require("./fileUtil");
var readFile=require('./readFile');
var uploadType=require('./uploadType');

var _404_html="./404/404_1.html";
var _prompt_html='./prompt/prompt_1.html';
var _erro_html='./error/err_1.html';


function route(handle,pathname,request,response){
	if(pathname=='/upload'){
		function callback(fields, response){
			uploadType.uploadSelect(fields, response);
		}
		fileUtil.saveFile(request,response,callback);
	}else{
		var postData="";
		request.setEncoding("utf8");
		request.addListener('data',function(postDataChunk){
			postData+=postDataChunk;
		});
		request.addListener('end',function(){
			if(typeof handle[pathname] ==='function'){
				handle[pathname](request,response);
			}else{
				if(pathname=='/favicon.ico'){
					response.write('You just visit \'/favicon.ico\'');
					response.end();
					return;
				}
				var fileType=pathname.substring(pathname.lastIndexOf('.')+1);
				pathname='.'+pathname;
				if(typeof Config.type[fileType] ==='string'){
					fs.exists(pathname,function(exists){
						if(!exists){
							//说明访问了空的文件
							readFile.readFile(_404_html,Config.type['text'],response);
						}else{
							readFile.readFile(pathname,Config.type[fileType],response);
						}
					});
				}else{
					readFile.readFile(_404_html,Config.type['text'],response);
				}
			}
		});
	}
}

exports.route=route;